<?php include 'functions.php'; echo $html_doctype; ?>
<html>
<head>
<?php
	dev_out('Server query string: '.$_SERVER['QUERY_STRING']);
	/*
	GET arguments can appear on different possions, mod_rewrited from e.g.:
	browse/sprites/newest            --> a, b
	browse/newest                    --> a
	browse/sprites/animation/newest  --> a,b,c
	-----------------------------------------------------------------------
	check argument type and put into array $arg[]
	arg order in url can be changed but type should always be before category.
	*/
	global $arg;
	if ($_GET['a']=='search') {
		$search_query = $_GET['b'];
	} else {
		if (isset($_GET['a'])) {
			$getarg = strtolower($_GET['a']);
			$arg[get_arg_type($getarg)] = $getarg;
		}
		if (isset($_GET['b'])) {
			$getarg = strtolower($_GET['b']);
			$arg[get_arg_type($getarg)] = $getarg;
		}
		if (isset($_GET['c'])) {
			$getarg = strtolower($_GET['c']);
			$arg[get_arg_type($getarg)] = $getarg;
		}
		if (isset($_GET['d'])) {
			$getarg = strtolower($_GET['d']);
			$arg[get_arg_type($getarg)] = $getarg;
		}
	}
	
	//page argument
	if (isset($arg['page'])) {
		$arg['page'] = $arg['page']-1;
	} else {
		$arg['page'] = 0;
	}
	//resource type argument
	if (isset($arg['type'])) {
		$arg['type'] = substr($arg['type'],0,strlen($arg['type'])-1); //remove ending s: 'sprites' --> 'sprite'
	} else {
		$arg['type'] = 'all';
	}
	//resource category argument - already checked by get_arg_type()	
	if (!isset($arg['category'])) {
		$arg['category'] = 'all';
	}			
	$order='ASC';
	//sorting
	if (isset($arg['sortby'])) {
		if ($arg['sortby']=='newest') {
			$arg['sortby']='id';
			$order='DESC';
		} elseif ($arg['sortby']=='name') {
			$arg['sortby']='title';
		}
	} else {
		$arg['sortby'] = 'id';
		$order='DESC';
	}
	
	if (isset($_GET['p'])) {
		$page = (int)$_GET['p'];
	} else {
		$page = 1;
	}
	
	if ($arg['sortby']=='id') {
		$pageTitle = 'Newest ';
	} elseif ($arg['sortby']=='title') {
		$pageTitle = 'Alphabetical ';
	} elseif ($arg['sortby']=='downloads') {
		$pageTitle = 'Most downloaded ';
	}
	
	if ($arg['type']=='all') {
		$pageTitle .= 'resources';
	} else {
		$pageTitle .= $arg['type'].'s';
	}
	
	if (isset($arg['search'])) {
		$arg['search'] = substr($arg['search'], strpos($arg['search'], '_')+1);
	}
	
	//HTML head
	echo "<title> Scratch Resources | $pageTitle </title>";
	echo $html_meta;
	echo $html_css;
	echo $html_scripts;
?>
<script type="text/javascript" src="/js/ressearch.js"></script>
</head>

<body>
<div id="maincontainer">
	<?php include 'header.php'; ?>
	
	<div class="res_search">
	<select onChange="res_search_restypeChanged()" id="restype_dropdown">
		<option value="all" selected="true">All resources</option>
		<option value="sprites">Sprites</option>
		<option value="scripts">Scripts</option>
		<option value="sounds">Sounds</option>
		<option value="backgrounds">Backgrounds</option>
	</select>
	<select onChange="res_search_categoryChanged()" disabled="true" id="category_dropdown">
		<option selected="true">Category...</option>
	</select>
	<span class="float_right">
	Search: <input id="res_search_field" type="text" onChange="res_search_searchChanged()"></input>
	</span>
	<!--<img src="/files/images/btn_search.png"></img>-->
	</div>
	
	<div class="box_fullwidth">
		
	<?php
	//echo vars for javascript
	echo '<script type="text/javascript">'."\n".
		 'res_search_restype="'.$arg['type'].'";'."\n".
		 'res_search_category="'.$arg['category'].'";'."\n".
		 'res_search_keywords="'.$arg['search'].'";'."\n".
		 'res_search_initfields()'.
		 '</script>'."\n\n";
		 
	echo '<span class="float_right">'."\n";
	//Sorting
	$myUrl = "/browse";
	if($arg['type']!='all') { $myUrl .= '/'.$arg['type'].'s'; }
	if($arg['category']!='all') { $myUrl .= '/'.$arg['category']; }
	if(isset($arg['search'])) { $myUrl .= '/search_'.$arg['search']; }
	
	echo "Sort by: ";
	echo '<a href="'.$myUrl.'/newest">Upload date</a> | ';
	echo '<a href="'.$myUrl.'/name">Name</a> | ';
	echo '<a href="'.$myUrl.'/downloads">Downloads</a>'."\n\n";
	echo "</span>\n";
	
	$rowsperpage = 10;
	
	resdap_connect();
	
	//Build the MySQL query for table res_resources
	$q = '';
	if ($arg['type']!='all') {
		$q .= "type='".mysql_real_escape_string($arg['type'])."' AND ";
	}
	if ($arg['category']!='all') {
		$q .= "category='".mysql_real_escape_string($arg['category'])."' AND ";
	}
	
	if (isset($arg['search'])) {
		$keywords = explode(' ', $arg['search']);
		$q .= '('; //include the search keywords in parentheses: blah AND (title LIKE keyword1 OR title LIKE keyword2...) AND blah
		foreach ($keywords as $keynum => $keyword) {
			if ($keynum != 0) {
				$q .= ' OR ';
			}
			$q .= "title LIKE '%".mysql_real_escape_string($keyword)."%'";
		}
		$q .= ') AND '; //close the search parentheses
	}
	
	
	if (resdap_user_haspermission('edit')) {
		$q .= "id>0 "; //easy dirty hack for showing all, no matter if hide is set to 1
	} else {
		$q .= "hide=0";
	}
	
	$query   = "SELECT COUNT(id) AS numrows FROM res_resources WHERE ".$q;
	$result  = mysql_query($query);
	dev_out("Query1: $query with potential error: ".mysql_error());
	$row     = mysql_fetch_array($result, MYSQL_ASSOC);
	$numrows = $row['numrows'];
	dev_out("Number of results: $numrows");
	
	$maxpage = ceil($numrows/$rowsperpage);
	$pagetxt = '';
	for ($i=1; $i<=$maxpage; $i++) {
	  	$pagetxt .= '<a href="'.$myUrl.'/'.$i.'">'.$i.'</a>';
	  	if ($i<$maxpage) {
		  	$pagetxt.= ' | ';
		}
	}
	$q = "SELECT * FROM res_resources WHERE ".$q;
	$q .= " ORDER BY ".$arg['sortby']." $order ";
	$q .= 'LIMIT '. ($arg['page']*$rowsperpage) .", $rowsperpage";
	dev_out("queried:<br> $q");
	$result = mysql_query($q);
	
	echo $pagetxt;
	
	if (mysql_num_rows($result)<1) {
		echo '<br><br><br><br><br> No results found. Broaden your search.';
	}
	
	while($row = mysql_fetch_array($result)) {
		
		//Query user data
		$q = "SELECT * FROM res_users WHERE id='".$row['user']."'";
		$user_result = mysql_query($q);
		$user_row = mysql_fetch_array($user_result);
		
		echo '<div class="result">'."\n";
		echo '<div class="thumb"><img src="/files/images/icon_'.$row['type'].'.png"></img></div>'."\n";
		//echo '<img src="/files/images/icon_'.$row['type'].'.png"></img>'."\n";
		echo '<div class="resultinfo">';
		echo '<b>'.$row['title'].'</b> by <a href="http://scratch.mit.edu/users/'. $user_row['username'] .'">'.$user_row['username'].'</a><br>'."\n";
		echo $row['comments']."<br> \n";
  		echo "</div>";
  		//toolbar
  		echo '<div class="resulttoolbar" ';
  		if ($row['type']=='sound') {
	  		echo 'style="width: 730px;"';
  		} else {
	  		echo 'style="width: 750px;"';
  		}
  		echo "> \n";
  		echo 'Download: <a href="/download?id='.$row['id'].'"><img src="/files/images/tb_icon_download.png" border="0"></img></a>'."\n";
  		if ($row['type']=='background') {
	  		echo 'View: <a href="javascript:previewImage('."'/download?id=".$row['id']."')".'"><img src="/files/images/tb_icon_view.png" border="0"></img></a>'."\n";
  		}
  		
  		if (resdap_user_haspermission('edit')) {
	  		echo 'Edit: <a href="/adminedit?id='.$row['id'].'"><img src="/files/images/tb_icon_edit.png" border="0"></img></a>'."\n";
	  		if ($row['hide']==1) {
	  			echo 'Show: <a href="'."javascript:resdap_showresource('".$row['id']."')".'"><img src="/files/images/tb_icon_show.png" border="0"></img></a>'."\n";
  			} else {
	  			echo 'Hide: <a href="'."javascript:resdap_hideresource('".$row['id']."')".'"><img src="/files/images/tb_icon_hide.png" border="0"></img></a>'."\n";
  			}
  		}
  		
  		if ($row['type']=='sound') {
	  		echo 'Listen:';
	  		echo '</div>';
	  		echo '<div class="miniplayer">';
			echo '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="20" height="20" id="player" align="middle">';
			echo '<param name="allowScriptAccess" value="sameDomain" /><param name="movie" value="http://resources.scratchr.org/files/miniplayer.swf" /><param name="quality" value="high" /><param name="wmode" value="transparent"><param name="bgcolor" value="#ffffff"><param name="flashvars" value="song='.$row['id'].'.'.$row['ext'].'&type='.$row['category'].'">';
			echo '<embed src="http://resources.scratchr.org/files/miniplayer.swf" quality="high" flashvars="song='.$row['id'].'.'.$row['ext'].'&type='.$row['category'].'" wmode="transparent" bgcolor="#ffffff" width="20" height="20" name="player" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></object>';
			echo '</div>';
		} else {
			echo '</div>';
		}
		//end toolbar
  		echo "</div> \n";  
  	}
 	
  	echo $pagetxt;
  	  	
  	dev_out('Mysql Error: '.mysql_error());
	resdap_disconnect();
	?>
	
	<div id="imgpreview"></div>
	
	</div>
	
	<?php include('footer.php'); ?>
</div>

</body>
</html>
